package sdk.webview.fmc.com.fmcsdk.check.persenter;


import android.text.TextUtils;
import android.util.Log;

import com.google.gson.Gson;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import rx.Observable;
import rx.singles.BlockingSingle;
import sdk.webview.fmc.com.fmcsdk.app.FMCApplication;
import sdk.webview.fmc.com.fmcsdk.base.BaseData;
import sdk.webview.fmc.com.fmcsdk.base.BasePresenter;
import sdk.webview.fmc.com.fmcsdk.base.UserApi;
import sdk.webview.fmc.com.fmcsdk.bean.DDTypeBean;
import sdk.webview.fmc.com.fmcsdk.bean.GetManagerBean;
import sdk.webview.fmc.com.fmcsdk.bean.OperateReportBean;
import sdk.webview.fmc.com.fmcsdk.bean.UnCheckPointBean;
import sdk.webview.fmc.com.fmcsdk.check.CacheHelper;
import sdk.webview.fmc.com.fmcsdk.check.bean.GetDetailsBean;
import sdk.webview.fmc.com.fmcsdk.check.bean.SelectOrderIdOrderPointBean;
import sdk.webview.fmc.com.fmcsdk.check.bean.WorkHistoryBean;
import sdk.webview.fmc.com.fmcsdk.check.interfaces.CheckDetailsView;
import sdk.webview.fmc.com.fmcsdk.check.listener.OnGetManagerCompleteListener;
import sdk.webview.fmc.com.fmcsdk.check.listener.OnGetSelectOrderIdOrderPointListener;
import sdk.webview.fmc.com.fmcsdk.check.listener.OnSubmitAcceptanceListener;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.GsonUtil;
import sdk.webview.fmc.com.fmcsdk.util.StringUtils;
import sdk.webview.fmc.com.fmcsdk.util.Url;
import sdk.webview.fmc.com.fmcsdk.util.UserHelper;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.observer.ResponseTransformer;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.subscriber.ResponseSubscriber;

/**
 * Created by ydm on 2017/9/14.
 */

public class CheckDetailsPersenter extends BasePresenter<CheckDetailsView> {


    public void getDetails(String id) {
        view.showLoading();
        getApi(UserApi.class).apiGetDetail(getDefaultAddress() + Url.GET_DETAILS, UserHelper.getToken(), id)
                .compose(new ResponseTransformer<>(this.<GetDetailsBean>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<GetDetailsBean>(view) {
                    @Override
                    public void success(GetDetailsBean baseData) {
                        if(view==null)return;
                        view.getDetails(baseData);
                        view.hideLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        view.hideLoading();
                    }

                    @Override
                    public void onRequestAgain() {

                    }
                });
    }


    //    @Query("id") String id,
//                                        @Query("taskId") String taskId,
//                                        @Query("orderOperate") String orderOperate,
//                                        @Query("operateTime") String operateTime,
//                                        @Query("actStartDate") String actStartDate,
//                                        @Query("remark") String remark,
//                                        @Query("code") String code,
//                                        @Query("type") String type,
//                                        @Query("isOffline") String isOffline
    public void getSpStatus(String id, String taskId, String orderOperate, String remark, String code, String projId, String actStartTime, String type, String sendStaffId,String gpsLocDesc, String lat, String lon) {
        view.showLoading();
        long time = System.currentTimeMillis() ;
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("taskId", taskId);
        map.put("orderOperate", orderOperate);
        map.put("operateTime", time+"");
        map.put("actStartDate", actStartTime);
        map.put("remark", remark);
        if (!StringUtils.isEmpty(gpsLocDesc)){
            map.put("gpsLocDesc",gpsLocDesc);
        }
        map.put("lat",lat);
        map.put("lon",lon);
        if (!code.equals("5")) {
            map.put("code", code);
        }
        if (!StringUtils.isEmpty(code) && !code.equals("5") && !orderOperate.equals("START")) {
            map.put("type", type);
        }

        if (!StringUtils.isEmpty(sendStaffId)) {
            map.put("sendStaffId", sendStaffId);
        }

        map.put("isOffline", "0");
        Log.e("huohuohuohuo",GsonUtil.BeanToJson(map));
        getApi(UserApi.class).apiGetSpStatus(getDefaultAddress() + Url.GET_SPSTATUS, UserHelper.getToken(), projId, map)
                .compose(new ResponseTransformer<>(this.bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<BaseData>(view) {
                    @Override
                    public void success(BaseData baseData) {
                        view.getSpStatus(orderOperate,time);
                        view.hideLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);

                        Map<String, Object> map = new HashMap<>();
                        map.put("projId", projId);
                        map.put("id", id);
                        map.put("taskId", taskId);
                        map.put("orderOperate", orderOperate);
                        map.put("time", time);
                        map.put("remark", remark);
                        map.put("code", code);
                        map.put("type", type);
                        map.put("isOffline", "0");
                        view.getSpStatusFail(new Gson().toJson(map));
                        view.hideLoading();
                    }

                    @Override
                    public void onRequestAgain() {

                    }
                });
    }



    public void getSpStatusSave(String id, String taskId, String orderOperate, String remark, String code, String projId, String actStartTime, String type, String sendStaffId,String gpsLocDesc, String lat, String lon,String des,String oooTime) {
       // String time = System.currentTimeMillis() + "";
        Map<String, Object> map = new HashMap<>();
        map.put("projId", projId);
        map.put("id", id);
        map.put("taskId", taskId);
        map.put("orderOperate", orderOperate);
        map.put("operateTime", oooTime);
        map.put("actStartDate", actStartTime);
        map.put("remark", remark);
        if (!StringUtils.isEmpty(gpsLocDesc)){
            map.put("gpsLocDesc",gpsLocDesc);
        }
        map.put("lat",lat);
        map.put("lon",lon);
        if (!code.equals("5")) {
            map.put("code", code);
        }
        if (!StringUtils.isEmpty(code) && !code.equals("5") && !orderOperate.equals("START")) {
            map.put("type", type);
        }
        if (!StringUtils.isEmpty(sendStaffId)) {
            map.put("sendStaffId", sendStaffId);
        }
        map.put("isOffline", "1");
        map.put("des", des);
        String json = new Gson().toJson(map);
        CacheHelper.getInstance().addStartPause(id, json,des);
    }



    public void getResult() {
        getApi(UserApi.class).getLangList(getDefaultAddress() + Url.GET_DD_LIST, Url.XMLHTTPREQUEST, UserHelper.getToken(), "SUSPEND_REMARK")
                .compose(new ResponseTransformer<>(this.<DDTypeBean>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<DDTypeBean>() {
                    @Override
                    public void success(DDTypeBean baseData) {
                        view.getResult(baseData);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }

                    @Override
                    public void onRequestAgain() {
                    }


                });


    }

    public void getOperateReportList() {
        view.showLoading();
        getApi(UserApi.class).getOperateReportList(getDefaultAddress() + Url.GET_OPERATE_REPORTSAS_LIST,  UserHelper.getToken(), "2")
                .compose(new ResponseTransformer<>(this.<OperateReportBean>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<OperateReportBean>() {
                    @Override
                    public void success(OperateReportBean baseData) {
                        if (null != baseData){
                            if (null != baseData.getRecords() && !baseData.getRecords().isEmpty()){
                                CacheHelper.getInstance().addMapJson("ReportList",GsonUtil.BeanToJson(baseData.getRecords()));
                                FMCApplication.shutDownList.clear();
                                FMCApplication.shutDownList.addAll(baseData.getRecords());
                            }
                        }
                        view.hideLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        view.hideLoading();
                    }

                    @Override
                    public void onRequestAgain() {
                    }


                });


    }

    public void getCommonDDListWithString() {
        getView().showLoading();
        getApi(UserApi.class).getLangList(getDefaultAddress() + Url.GET_DD_LIST, Url.XMLHTTPREQUEST, UserHelper.getToken(), "INSP_CHECK_RESULT_TYPE")
                .compose(new ResponseTransformer<>(this.<DDTypeBean>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<DDTypeBean>() {
                    @Override
                    public void success(DDTypeBean baseData) {
                        getView().hideLoading();
                        List<DDTypeBean.RecordsBean> records = baseData.getRecords();
                        if (!records.isEmpty()) {
                            for (int i = 0; i < records.size(); i++) {
                                String code = records.get(i).getCode();
                                Log.e("huohuohuo", "code===" + code);
                                if (!StringUtils.isEmpty(code)) {
                                    loadSingleCheckResult(code);
                                }
                            }
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }

                    @Override
                    public void onRequestAgain() {
                    }


                });


    }

    private void loadSingleCheckResult(String ddType) {
        getView().showLoading();
        getApi(UserApi.class).getLangList(getDefaultAddress() + Url.GET_DD_LIST, Url.XMLHTTPREQUEST, UserHelper.getToken(), ddType)
                .compose(new ResponseTransformer<>(this.<DDTypeBean>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<DDTypeBean>() {
                    @Override
                    public void success(DDTypeBean baseData) {
                        getView().hideLoading();
                        Log.e("huohuohuo", new Gson().toJson(baseData.getRecords()));
                        List<DDTypeBean.RecordsBean> records = baseData.getRecords();
                        CacheHelper.getInstance().addMapJson(ddType,GsonUtil.BeanToJson(records));
                        FMCApplication.typeMap.put(ddType, records);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                    }

                    @Override
                    public void onRequestAgain() {
                    }


                });

//// 创建 OkHttpClient 实例
//        OkHttpClient client = new OkHttpClient();
//
//        // 请求的 URL 和查询参数
//        String url = getDefaultAddress()+ Url.GET_DD_LIST+"?ddtype="+ddType;  // 替换为你的实际 URL
//
//        // 构建请求
//        Request request = new Request.Builder()
//                .url(url)  // 设置请求的 URL
//                .addHeader("X-Requested-With", Url.XMLHTTPREQUEST)  // 设置自定义请求头
//                .addHeader("accessToken", UserHelper.getToken())  // 设置 accessToken 请求头
//                .build();
//        Log.e("huohuohuohuo","Response: " + 111111);
//        // 使用同步方式执行请求
//        try {
//            Response response = client.newCall(request).execute();
//            if (response.isSuccessful()) {
//                // 打印返回的数据
//                Log.e("huohuohuohuo","Response: " + response.body().string());
//            } else {
//                Log.e("huohuohuohuo","Request failed with code: " + response.code());
//            }
//        }catch (IOException e){
//            Log.e("huohuohuohuo","error " + e.getMessage());
//            e.printStackTrace();
//        }
    }


    public void getManager(String staffId) {
        view.showLoading();
        getApi(UserApi.class).getManager(getDefaultAddress() + Url.GET_MANAGER, UserHelper.getToken(), UserHelper.getToken(), staffId)
                .compose(new ResponseTransformer<>(this.<GetManagerBean>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<GetManagerBean>() {
                    @Override
                    public void success(GetManagerBean baseData) {
                        view.getManagerSuccess(baseData.getRecord());
                        view.hideLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        if(view==null)return;
                        view.hideLoading();
                    }

                    @Override
                    public void onRequestAgain() {
                    }


                });

    }


    public void getUnCheckPoint(String projid, String id) {
        view.showLoading();
        getApi(UserApi.class).getUnCheckPoint(getDefaultAddress() + Url.GET_UNCHECK_POINT, UserHelper.getToken(), projid, id)
                .compose(new ResponseTransformer<>(this.<UnCheckPointBean>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<UnCheckPointBean>() {
                    @Override
                    public void success(UnCheckPointBean baseData) {
                        view.getUnCheckPointSuccess(baseData.getRecords());
                        view.hideLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        view.hideLoading();
                    }

                    @Override
                    public void onRequestAgain() {
                    }


                });
    }


    public void getCheckComplete(String projid, String id, String taskId, String compRemark, long operateTime, String pushStaffIds) {
        view.showLoading();
        getApi(UserApi.class).getCheckComplete(getDefaultAddress() + Url.GET_CHECK_COMPLETE, UserHelper.getToken(), projid, id, taskId, compRemark, operateTime + "", "0", pushStaffIds)
                .compose(new ResponseTransformer<>(this.<BaseData>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<BaseData>() {
                    @Override
                    public void success(BaseData baseData) {
                        view.getCheckCompleteSuccess();
                        view.hideLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        view.hideLoading();
                    }

                    @Override
                    public void onRequestAgain() {
                    }


                });
    }


    //更新点位
    public void updateInspectionPoint(String projid,
                                      Long actUploadDate,
                                      List<GetDetailsBean.RecordDTO.PointsDTO.CheckListDTO> checkList,
                                      Long finishDate,
                                      String id,
                                      Integer isSkip,
                                      String orderId,
                                      String quRemake,
                                      String status) {
        view.showLoading();

        HashMap<String, Object> map = new HashMap<>();
        map.put("actUploadDate", actUploadDate);
        map.put("checkList", checkList);
        map.put("finishDate", finishDate);
        map.put("id", id);
        map.put("isSkip", isSkip);
        map.put("orderId", orderId);
        map.put("remake", quRemake);
        map.put("status", status);

        Log.e("霍东升检查参数:", new Gson().toJson(map));

        RequestBody requestBody = RequestBody.create(MediaType.parse("raw"), new Gson().toJson(map));

        getApi(UserApi.class).updateInspectionPoint(getDefaultAddress() + Url.POST_UPDATE_POINT, UserHelper.getToken(), projid, requestBody)
                .compose(new ResponseTransformer<>(this.bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<BaseData>(view) {
                    @Override
                    public void success(BaseData baseData) {
                        view.updatePointSuccess();
                        view.hideLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        map.put("projid", projid);
                        view.updatePointFail(map);
                        view.hideLoading();
                    }

                    @Override
                    public void onRequestAgain() {

                    }
                });
    }

    public void getSelectOrderIdOrderPoint(String orderId, String projId, OnGetSelectOrderIdOrderPointListener listener) {
        view.showLoading();
        getApi(UserApi.class).getSelectOrderIdOrderPoint(
                        getDefaultAddress() + Url.GET_SELECT_ORDER_ID_ORDER_POINT,
                        UserHelper.getToken(),
                        projId, orderId, projId)
                .compose(new ResponseTransformer<>(this.bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<SelectOrderIdOrderPointBean>() {
                    @Override
                    public void success(SelectOrderIdOrderPointBean baseData) {
                        Log.e("hahahhaha", GsonUtil.BeanToJson(baseData));
                        listener.OnSuccessListener(baseData.getRecord());
                        view.hideLoading();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        view.hideLoading();
                    }

                    @Override
                    public void onRequestAgain() {
                    }


                });

    }

    public void submitAcceptance(String projId, Map<String, String> map, OnSubmitAcceptanceListener listener) {
        Log.e("huohuohuohuohuo",GsonUtil.BeanToJson(map));
        //RequestBody requestBody = RequestBody.create(MediaType.parse("raw"), new Gson().toJson(map));
        Map<String, RequestBody> stringRequestBodyMap = StringUtils.generateRequestBody(map);
        view.showLoading();
        getApi(UserApi.class).submitAcceptance(getDefaultAddress() + Url.POST_SUBMIT_ACCEPTANCE, UserHelper.getToken(), projId, stringRequestBodyMap)
                .compose(new ResponseTransformer<>(this.bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<BaseData>() {
                    @Override
                    public void success(BaseData baseData) {
                        view.hideLoading();
                        listener.submitAcceptanceCallback();
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        view.hideLoading();
                    }

                    @Override
                    public void onRequestAgain() {
                    }


                });
    }

    public void getDetailsHistory(String id,String projId) {
        getApi(UserApi.class).apiGetHistory(getDefaultAddress() + Url.GET_HISTORY, UserHelper.getToken(), Long.valueOf(id),projId)
                .compose(new ResponseTransformer<>(this.<WorkHistoryBean>bindToLifeCycle()))
                .subscribe(new ResponseSubscriber<WorkHistoryBean>(view) {
                    @Override
                    public void success(WorkHistoryBean baseData) {
                        view.getHistory(baseData,id,projId);
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);

                    }

                    @Override
                    public void onRequestAgain() {

                    }
                });
    }

}
